<template>
  <el-dialog :visible.sync="visible" :title="$t('user.userDataScope')" :close-on-click-modal="false"
    :close-on-press-escape="false">
    <el-form v-loading="loading" ref="dataScope" :label-width="$i18n.locale === 'en-US' ? '120px' : '100px'">
      <el-form-item v-for="(item) in this.dataForm.list" :key="item.id" :label="item.ruleSortName">
        <el-col :span="24">
          <uni-tree-select v-model="item.customDataIds" :selectParams="{ multiple: true}" :treeParams="{ clickParent: true,'check-strictly':true}"
            :data="item.treeData" />
        </el-col>
      </el-form-item>
      <el-form-item>
        <el-button @click="visible = false">{{ $t('cancel') }}</el-button>
        <el-button v-if="!readOnly" type="primary" @click="formSubmitHandle()">{{ $t('confirm') }}</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script>
import debounce from 'lodash/debounce'
export default {
  data () {
    return {
      loading: false,
      visible: false,
      dataForm: {
      }
    }
  },
  props: {
    readOnly: {
      type: Boolean,
      required: false,
      default: function () {
        return true
      }
    }
  },
  computed: {
    dataRule () {
      return {}
    }
  },
  methods: {
    init () {
      this.visible = true
      this.$nextTick(() => {
        this.$refs['dataScope'].resetFields()
        if (this.userId) {
          this.getInfo()
        }
      })
    },
    // 获取信息
    getInfo () {
      this.loading = true
      this.$http.get(`sys/sysUserCustrule/genList`, { params: { userId: this.userId } }).then(({ data: res }) => {
        this.loading = false
        if (res.code !== 0) {
          return
        }
        this.dataForm = res.data
      }).catch(() => { this.loading = false })
    },
    // 表单提交
    formSubmitHandle: debounce(function () {
      this.loading = true
      this.$confirm(this.$t('prompt.info', { 'handle': this.$t('save') }), this.$t('prompt.title'), {
        confirmButtonText: this.$t('confirm'),
        cancelButtonText: this.$t('cancel'),
        type: 'warning'
      }).then(() => {
        this.dataForm.userId = this.userId
        this.$http.post('/sys/sysUserCustrule', this.dataForm).then(({ data: res }) => {
          this.loading = false
          if (res.code !== 0) {
            return false
          }
          this.$message({
            message: this.$t('prompt.success'),
            type: 'success',
            duration: 500,
            onClose: () => {
              this.visible = false
            }
          })
        }).catch(() => { this.loading = false })
      }).catch(() => { this.loading = false })
    }, 1000, { 'leading': true, 'trailing': false })
  }
}
</script>

<style lang="scss">
</style>
